// 文件上传模块
const express = require("express");
const serve = express();

// 设置端口
serve.listen(3040, () => {
  console.log("文件上传服务器启动成功");
});

const cors = require("cors");
// 解决跨域
serve.use(cors());

// 静态资源管理
serve.use(express.static("./public"));
serve.use(express.static("./upload"));

// 引入uuid模块 npm i uuid
const uuid = require("uuid");
// 引入multer 模块 npm i multer
const multer = require("multer");
// 用一个变量接收上传对象
const upload = multer({
  // 文件存储位置
  storage: multer.diskStorage({
    // 存储文件夹
    destination: "upload",
    // 获取上传文件信息
    filename(req, uploadInfo, cb) {
      // 需要解决中文,生成唯一id
      let { originalname } = uploadInfo;
      // 设置uuid + '_' + 中文
      let name =
        uuid.v4() + "_" + Buffer.from(originalname, "latin1").toString("utf-8");
      // 执行存储名字回调
      cb(null, name);
    },
  }),
});


// 访问静态资源   
const path = require('path')
serve.get('/upload/:name', (req, res) => {
  let { name } = req.params
  console.log(req.params);
  res.sendFile(path.join(__dirname, '/upload/' + name))
})

// 开启请求地址
serve.use("/upload", upload.array("uploadInfo"), (req, res) => {
  // 上传到信息存在了req.files中
  res.send({ code: 200, data: req.files });
});
